package com.xk.meeting.back.controller;

import com.xk.meeting.entity.Admin;
import com.xk.meeting.entity.User;
import com.xk.meeting.utils.UtilHelper;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@WebFilter(urlPatterns = "/back/*",initParams = {@WebInitParam(name = "url",value = "css,layui,images,login,index.jsp")})
public class LoginFilter implements Filter {
    private List<String> urls;
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;

        String requestURI = request.getRequestURI();

        if (UtilHelper.contains(requestURI,urls)){
            chain.doFilter(request, response);
        }else {
            HttpSession session = request.getSession();
            Admin admin = (Admin) session.getAttribute("admin");
            if (admin != null){
                chain.doFilter(request,response);
            }else {
                response.sendRedirect("login.jsp");
            }
        }
    }

    public void init(FilterConfig config) throws ServletException {
        String url = config.getInitParameter("url");
        String[] split = url.split(",");
        urls = Arrays.asList(split);
    }

}
